<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    ></ProTable>
    <el-dialog v-model="dialogVisible" title="商品预览" width="800" :align-center="true">
      <div style="max-height: 500px; overflow: auto">
        <!-- 销售单 -->
        <div v-if="dialogContent.positiveOrder.length" class="order-container positive-order">
          <div class="order-title">销售单详情</div>
          <div v-for="(item, index) in dialogContent.positiveOrder" :key="index" class="goods-item">
            <div class="goods-name">商品名称：{{ item.name1 }} / {{ item.tiaoma1 }} {{ item.symbol }}</div>
            <div class="goods-price">价格信息：{{ item.unit_price }} / {{ item.original_price }} / x{{ item.buyNum }}</div>
          </div>
        </div>
        <!-- 退款单 -->
        <div v-if="dialogContent.negativeOrder.length" class="order-container negative-order">
          <div class="order-title">退款单详情</div>
          <div v-for="(item, index) in dialogContent.negativeOrder" :key="index" class="goods-item">
            <div class="goods-name">商品名称：{{ item.name1 }} / {{ item.tiaoma1 }} {{ item.symbol }}</div>
            <div class="goods-price">价格信息：{{ item.unit_price }} / {{ item.original_price }} / x{{ item.buyNum }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import numeral from "numeral";
import { User } from "@/api/interface";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getOrderList } from "@/api/modules/datawarn";
import ShowChileDate from "@/components/ShowChileDate/index.vue";
dayjs.extend(utc);
dayjs.extend(timezone);
// ProTable 实例
const dialogVisible = ref(false);
const dialogContent: any = ref({});
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  pageNum: 1,
  pageSize: 10
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  let startTime: any = undefined;
  let endTime: any = undefined;
  if (newParams.created_at) {
    startTime = dayjs.tz(newParams.created_at, "America/Santiago").startOf("day").unix();
    endTime = dayjs.tz(newParams.created_at, "America/Santiago").endOf("day").utc().unix();
    delete newParams.created_at;
  }
  const pageParams = {
    is_exchange: newParams.is_exchange,
    type: newParams.type,
    start_time: startTime,
    end_time: endTime,
    limit: newParams.pageSize,
    page: newParams.pageNum
  };
  return getOrderList(pageParams);
};
const handleViewDataBox = record => {
  dialogVisible.value = true;
  let showParams: any = {
    positiveOrder: [],
    negativeOrder: []
  };
  let newList: any[] = [];
  if (record.positive_order) {
    showParams.positiveOrder = [];
    JSON.parse(record.positive_order).forEach(item => {
      if (item.is_back === 1) {
        newList.push(item);
      } else {
        showParams.positiveOrder.push(item);
      }
    });
  }
  if (record.negative_order) {
    showParams.negativeOrder = [];
    showParams.negativeOrder = JSON.parse(record.negative_order) || [];
  }
  if (newList.length > 0) {
    showParams.negativeOrder = [...showParams.negativeOrder, ...newList];
  }
  dialogContent.value = showParams;
};
const getPayTypeText = (type: number) => {
  if (type === 1) {
    return "现金";
  }
  if (type === 2) {
    return "信用卡";
  }
  if (type === 3) {
    return "储蓄卡";
  }
  if (type === 7) {
    return "混合支付";
  }
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "id", label: "ID", width: 50 },
  {
    prop: "shopId",
    label: "店铺ID",
    width: 180,
    render: (scope: any) => {
      if (scope.row.shop_id) {
        return `${scope.row.shop_id} / ${scope.row.shop_name}`;
      }
      return "";
    }
  },
  {
    prop: "id",
    label: "销售类型",
    width: 100,
    search: {
      // 自定义 search 显示内容
      render: ({ searchParam }) => {
        return (
          <div>
            <el-select v-model={searchParam.type} placeholder="请选择订单类型" clearable>
              <el-option key="1" label="销售单" value={1} />
              <el-option key="2" label="退货单" value={2} />
            </el-select>
          </div>
        );
      }
    },
    render: (scope: any) => {
      if (scope.row.is_exchange === 1) {
        return "换货订单";
      }
      if (scope.row.type === 1) {
        return "销售单";
      }
      if (scope.row.type === 2) {
        return "退单";
      }
      return "";
    }
  },
  {
    prop: "out_trade_no",
    label: "订单号",
    width: 150,
    search: {
      // 自定义 search 显示内容
      render: ({ searchParam }) => {
        return (
          <div class="">
            <el-select v-model={searchParam.is_exchange} placeholder="是否换货" clearable>
              <el-option key="1" label="是" value={1} />
              <el-option key="2" label="否" value={2} />
            </el-select>
          </div>
        );
      }
    },
    render: (scope: any) => {
      if (scope.row.out_trade_no1) {
        return `${scope.row.out_trade_no} / ${scope.row.out_trade_no1}`;
      }
      return scope.row.out_trade_no;
    }
  },
  {
    prop: "end_fee",
    label: "结算金额(Peso)",
    width: 150,
    render: (scope: any) => {
      return `${getPayTypeText(scope.row.pay_type)}: ${numeral(scope.row.end_fee).format("0,0")}`;
    }
  },
  {
    prop: "end_fee",
    label: "实付/找零(Peso)",
    width: 150,
    render: (scope: any) => {
      let userPayMoney = 0;
      if (scope.row.pay_type === 1) {
        userPayMoney = scope.row.net_amount;
      }
      if (scope.row.pay_type === 2) {
        userPayMoney = scope.row.end_fee;
      }
      if (scope.row.pay_type === 3) {
        userPayMoney = scope.row.end_fee;
      }
      if (scope.row.pay_type === 7) {
        userPayMoney = scope.row.end_fee;
      }
      return `${numeral(userPayMoney).format("0,0")}/${numeral(scope.row.give_change).format("0,0")}`;
    }
  },
  {
    prop: "file_path",
    label: "商品数据",
    width: 100,
    render: (scope: any) => {
      let goodsLengthText = 0;
      if (scope.row.positive_order) {
        let pOrder = JSON.parse(scope.row.positive_order);
        goodsLengthText = pOrder.length;
      }
      if (scope.row.negativeOrder) {
        let pOrder = JSON.parse(scope.row.negativeOrder);
        goodsLengthText = pOrder.length;
      }
      return (
        <el-button type="primary" size="small" onClick={() => handleViewDataBox(scope.row)}>
          {goodsLengthText}件
        </el-button>
      );
    }
  },
  {
    prop: "os_info",
    label: "关键参数",
    render: (scope: any) => {
      let params: any = {};
      if (scope.row.os_info) {
        params = JSON.parse(scope.row.os_info);
      }
      let showList: any[] = [];
      if (params) {
        showList.push({
          label: "App版本",
          value: `${params.appVersion}/${params.appLanguage}`
        });
        showList.push({
          label: "收银机系统",
          value: `${params.osName}/${params.osVersion}/${params.windowWidth}x${params.windowHeight}`
        });
      }
      if (showList.length > 0) {
        return (
          <div className="flex">
            {showList.map((item, index) => {
              return (
                <div key={index}>
                  {item.label}: {item.value}
                </div>
              );
            })}
          </div>
        );
      }
      return "";
    }
  },
  {
    prop: "created_at",
    label: "日期(时区:America/Santiago)",
    search: {
      el: "date-picker",
      span: 1,
      props: { type: "date", valueFormat: "YYYY-MM-DD" }
    },
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.order_create_time} />;
    }
  }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
</script>

<style scoped>
.order-container {
  padding: 12px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.positive-order {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}
.negative-order {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}
.order-title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #333333;
}
.goods-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;
}
.goods-item:last-child {
  border-bottom: none;
}
.goods-name {
  margin-bottom: 4px;
  color: #606266;
}
.goods-price {
  font-size: 13px;
  color: #909399;
}
</style>
